import React, { PureComponent } from 'react';
import { ListView } from 'antd-mobile';

const texts = {
  loading: '加载中',
  loaded: ''
};

class List extends PureComponent {
    page = 1;

    constructor(props) {
      super(props);

      const datasource = new ListView.DataSource({
        rowHasChanged: (r1, r2) => r1 !== r2
      });

      this.state = {
        datasource
      };

      this.loadMore = this.loadMore.bind(this);
    }

    componentDidMount() {
      // 是否默认初始加载1次
      const { disabledFirst = false } = this.props;
      if (disabledFirst) return false;
      const { initPage = this.page } = this.props;
      this.props.onEndReached(initPage);
    }

    loadMore() {
      if (!this.props.hasMore) {
        return;
      }
      this.props.onEndReached(++this.page);
    }

    render() {
      let data = this.state.datasource.cloneWithRows(this.props.data);
      const { clsName = '' } = this.props;
      return data ? (
        <ListView
          ref={el => (this.lv = el)}
          dataSource={data}
          renderFooter={() => (
            <div style={{ padding: 10, textAlign: 'center' }}>
              {this.state.isLoading ? texts.loading : texts.loaded}
            </div>
          )}
          onClick={this.props.onClick}
          renderRow={this.props.renderItem}
          className={`am-list ${clsName}`}
          useBodyScroll
          scrollRenderAheadDistance={500}
          onEndReached={this.loadMore}
          onEndReachedThreshold={10}
        />
      ) : (
        this.props.children
      );
    }
}

export default List;
